package cn.com.dingtek.genius.manager.server.service;

import cn.com.dingtek.genius.manager.server.repository.db.entity.AuthGroupRule;
import cn.com.dingtek.genius.manager.server.repository.db.entity.AuthRule;
import cn.com.dingtek.genius.manager.server.repository.db.manager.AuthGroupRuleManager;
import cn.com.dingtek.genius.manager.server.repository.db.manager.AuthRuleManager;
import cn.com.dingtek.genius.manager.server.support.AuthRuleType;
import cn.com.dingtek.genius.manager.server.utils.MybatisPlusUtil;
import cn.com.dingtek.genius.manager.server.utils.Verify;
import cn.com.dingtek.genius.manager.server.utils.VerifyException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AuthRuleService {

    @Autowired
    private AuthRuleManager authRuleManager;
    @Autowired
    private AuthGroupRuleManager authGroupRuleManager;

    public JSONObject list(AuthRule param, Long groupId, int currentPage, int pageSize) {
        QueryWrapper<AuthRule> query = Wrappers.emptyWrapper();
        if (param != null) {
            query = MybatisPlusUtil.customLikeQuery(null, "rule_name", param.getRuleName());
            query = MybatisPlusUtil.customLikeQuery(query, "rule_code", param.getRuleCode());
        }

        IPage<AuthRule> page = authRuleManager.page(new Page<AuthRule>(currentPage, pageSize).setAsc("id"), query);

        List<JSONObject> records = page.getRecords().stream().map(item -> {
            JSONObject jsonObject = (JSONObject) JSON.toJSON(item);
            jsonObject.fluentPut("ruleTypeDesc", AuthRuleType.valueOf(item.getRuleType()).getDesc());

            if (groupId != null) {
                AuthGroupRule authGroupRule = authGroupRuleManager.getAuthGroupRule(groupId, item.getId());
                if (authGroupRule != null) {
                    jsonObject.fluentPut("is_grant", true);
                } else {
                    jsonObject.fluentPut("is_grant", false);
                }
            }

            return jsonObject;
        }).collect(Collectors.toList());
        return new JSONObject().fluentPut("total", page.getTotal())
                .fluentPut("records", records);
    }


    public void add(AuthRule param, Date now) {
        try {
            Verify.isTrue(authRuleManager.save(AuthRule.builder()
                    .ruleName(param.getRuleName())
                    .ruleCode(param.getRuleCode())
                    .ruleType(param.getRuleType())
                    .ruleCondition(param.getRuleCondition())
                    .remark(param.getRemark())
                    .valid(1)
                    .ctime(now)
                    .utime(now)
                    .version(0)
                    .build()), "新增权限失败。");
        } catch (DuplicateKeyException e) {
            throw new VerifyException("该权限码已存在。");
        }
    }

    public AuthRule info(Long id) {
        Verify.isTrue(id != null && id > 0, "权限不存在");
        return authRuleManager.getById(id);
    }

    public void update(AuthRule param, Date now) {
        Verify.isTrue(param.getId() != null && param.getId() > 0, "权限不存在");

        AuthRule authRule = authRuleManager.getById(param.getId());
        Verify.notNull(authRule, "权限不存在");

        AuthRule toUpdate = AuthRule.builder()
                .id(param.getId())
                .ruleName(param.getRuleName())
                .ruleCode(param.getRuleCode())
                .ruleType(param.getRuleType())
                .ruleCondition(param.getRuleCondition())
                .remark(param.getRemark())
                .utime(now)
                .version(authRule.getVersion()).build();

        Verify.isTrue(authRuleManager.updateById(toUpdate), "更新角色失败");
    }

    public void remove(Long id) {
        if (id != null && id > 0) {
            AuthRule authRule = authRuleManager.getById(id);
            if (authRule != null) {
                Verify.isTrue(!authRule.getDelLock(), "该权限为系统默认权限，不能被删除");
                authRuleManager.removeById(id);
            }
        }
    }
}
